package com.farm.filter;

import com.alibaba.fastjson.JSON;


import com.farm.common.BaseContext;
import com.heima.common.exception.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@Component
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //路径匹配器
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {


        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取请求的url
        String requestURI = request.getRequestURI();
        log.info("本次拦截:{}",requestURI);

        String[] urls = new String[]{
                "/user/user/login",
        };

        //判断路径匹配
        boolean check = check(urls, requestURI);

        //如果不需要处理
        if(check){
            filterChain.doFilter(request,response);
            return;
        }
        //获取 header里的token
        String token = request.getHeader("authorization");
        log.info(token);
        //判断是否登录了
        if(request.getSession().getAttribute("employee")!= null ){

            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);

            filterChain.doFilter(request,response);
            return;
        }
        if(request.getSession().getAttribute("user")!= null ){

            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request,response);
            return;
        }

        //如果未登录,通过输出流
        response.getWriter().write(JSON.toJSONString(ResponseResult.okResult("NOTLOGIN")));
        return;
    }

    /**
     * 路径匹配方法
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls,String requestURI){
        for(String url : urls){
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match){
                return match;
            }
        }
        return false;
    }
}
